﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;
using System.Web; 
using CoolCode.Reflection;

namespace CoolCode.Caching
{
    public class CacheFactory
    {
        private static ICacheStrategy instance;

        public static ICacheStrategy CreateInstance(string binDirectory)
        {
            if (instance == null)
            {
                string cacheSetting = ConfigurationManager.AppSettings["Cache"];
                if (string.IsNullOrEmpty(cacheSetting))
                    return null;
                //   throw new NullReferenceException ("No cache setting! Please add <add key=\"Cache\" value=\"Cache class,Cache assembly name\"/> in <appSettings>");
                string typeName;
                string assemblyName;
                if (cacheSetting.Contains(","))
                {
                    var s = cacheSetting.Split(',');
                    typeName = s[0];
                    assemblyName = s[1];
                }
                else
                {
                    typeName = cacheSetting;
                    assemblyName = typeName.GetNamespace();
                }
                if (String.IsNullOrEmpty(typeName) || String.IsNullOrEmpty(assemblyName))
                    return null;
                string assemblyFile = System.IO.Path.Combine(binDirectory, assemblyName);
                instance = AssemblyFactory.CreateInstance<ICacheStrategy>(typeName, assemblyName);
            }
            return instance;
        }

        /*
        public static ICacheStrategy CreateInstance()
        {
            if (instance == null)
            {
                string cacheSetting = ConfigurationManager.AppSettings["Cache"];
                if (string.IsNullOrEmpty(cacheSetting))
                    return null;
                 //   throw new NullReferenceException ("No cache setting! Please add <add key=\"Cache\" value=\"Cache class,Cache assembly name\"/> in <appSettings>");
                string typeName;  
                string assemblyName;
                if (cacheSetting.Contains(","))
                {
                    var s = cacheSetting.Split(',');
                    typeName = s[0];
                    assemblyName = s[1];
                }
                else
                {
                    typeName = cacheSetting;
                    assemblyName = typeName.GetNamespace();
                }
                if (String.IsNullOrEmpty(typeName) || String.IsNullOrEmpty(assemblyName))
                    return null;
                instance = AssemblyFactory.CreateInstance<ICacheStrategy>(typeName, assemblyName);
            }
            return instance;
        }
        */
         
    }
}
